<template>
  <section class="check-lists"
           :style="orgin.slotTab ? 'padding-bottom:80px' :''">
    <div v-if="orgin.limit > 1 && orgin.dataList.lenght > 0"
         @click="judgeAllDisable($event, isIndeterminate)">
      <a-checkbox :checked="isIndeterminate"
                  v-model="checkAll"
                  @change="handleCheckAllChange">
        全选
      </a-checkbox>
    </div>
    <a-checkbox-group v-model="checkedItems"
                      @change="handleCheckedCitiesChange">
      <div v-for="item in orgin.dataList"
           :key="item"
           @click="judgeDisable($event, item)"
           :title="orgin.labelDataList[item][pro.name]">
        <a-checkbox :value="item"
                    @change="handleCheckedChange"
                    :disabled="orgin.attrs.type == 'user' && orgin.limit == '1' &&
                      orgin.labelDataList[item].type == '1' ||
                      orgin.needUnitType == '2' && orgin.labelDataList[item].unitType == '1' || orgin.needUnitType == '3' &&
                      (orgin.labelDataList[item].unitType == '1' || orgin.labelDataList[item].unitType == '2') ||
                      orgin.disabledId.includes(orgin.labelDataList[item].id)">
          <span class="icon-user">
            <i class="el-icon-user"
               v-show="orgin.labelDataList[item].type && orgin.labelDataList[item].type == 2"></i>
            {{ orgin.labelDataList[item][pro.name] }}
            <!-- <span v-if="
                orgin.labelDataList[item].type &&
                  orgin.labelDataList[item].type == 1
              ">{{ "(" + orgin.labelDataList[item].personCount + "人)" }}</span> -->
          </span>
          <div class="link-bottom"
               style="cursor:pointer;"
               @click.stop.prevent="getSubordinateData(item)"
               v-if="!orgin.labelDataList[item].type || (orgin.labelDataList[item].type && orgin.labelDataList[item].type == 1)">
            下级
          </div>
        </a-checkbox>
      </div>
    </a-checkbox-group>
  </section>
</template>

<script>

import { message } from 'ant-design-vue'
import PropTypes from '@zh/common-utils/prop-types'

export default {
  components: { message },

  name: 'UserUnitListAntD',
  props: {
    // 菜单
    breadcrumbLists: PropTypes.array.def([]),
    pro: PropTypes.object.def({
      id: 'id',
      name: 'name'
    }),
    notAllowed: PropTypes.array.def([])
  },
  // 导入祖父级定义的名称
  inject: ['orgin', 'dialog'],
  data () {
    return {
      checkAll: false,
      ischecked: false,
      // 当前列表选中数据
      checkedItems: [],
      isIndeterminate: false
    }
  },
  watch: {
    // dataList,更新选中数据
    'orgin.dataList': {
      handler (val) {
        this.updateAllCheck()
      }
    },
    // // 监听tagLists,刷新列表选中状态
    'dialog.tagLists': {
      handler (value) {
        this.checkedItems = value
        this.updateAllCheck()
      }
    },
  },
  computed: {

  },
  mounted () {
    this.checkedItems = this.dialog.tagLists
  },
  methods: {
    // 单选
    handleCheckedChange (val) {
      if (val.target.checked) {
        // 合并数组并去重
        if (this.dialog.tagLists.indexOf(val.target.value) == -1) {
          this.dialog.tagLists.push(val.target.value)
        }
      } else {
        this.dialog.tagLists.splice(
          this.dialog.tagLists.indexOf(val.target.value),
          1
        )
        if (this.orgin?.slotTab) {
          this.orgin.slotTab.map(item => {
            let ind = null
            item.data.map((data, index) => {
              if (data.id == val.target.value) {
                ind = index
                return
              }
            })
            if (ind) {
              item.data.splice(ind, 1)
            }
          })
        }
      }
    },
    // 全选
    handleCheckAllChange (val) {
      if (val.target.checked) {
        // this.isIndeterminate = true
        // 合并数组并去重
        this.orgin.dataList.forEach((item) => {
          if (this.dialog.tagLists.indexOf(item) == -1) {
            if (this.orgin.limit > 0 && this.dialog.tagLists.length < this.orgin.limit) {
              this.dialog.tagLists.push(item)
            } else if (this.orgin.limit == 0) {
              this.dialog.tagLists.push(item)
            }
          }
        })
      } else {
        // 删除已选中包含当前列表的数据
        for (let i = 0; i < this.orgin.dataList.length; i++) {
          for (let j = 0; j < this.dialog.tagLists.length; j++) {
            if (this.dialog.tagLists[j] == this.orgin.dataList[i]) {
              this.dialog.tagLists.splice(j, 1)
            }
          }
        }
        this.isIndeterminate = false
      }
    },
    // 判断是否全选，更新全选状态
    handleCheckedCitiesChange (value) {
      // this.updateAllCheck()
      const arr = this.dialog.tagLists.filter((num) => {
        return this.orgin.dataList.indexOf(num) !== -1
      })

      this.isIndeterminate =
        arr.length > 0 && arr.length < this.orgin.dataList.length
      this.checkedItems = this.dialog.tagLists
    },
    // 获取下级数据
    getSubordinateData (item) {
      // 禁止选择点击下级
      if (this.dialog.tagLists.indexOf(item) != -1) {
        return
      }
      // 更新导航数据
      // eslint-disable-next-line vue/no-mutating-props
      this.breadcrumbLists.push(item)

      // 加载列表数据
      this.orgin.loadNode(item, this.orgin.needUnitType)
    },
    updateAllCheck () {
      // 判断是否全选
      this.checkAll = this.orgin.dataList.every((val) =>
        this.dialog.tagLists.includes(val)
      )
      // 判断是否有选中
      if (!this.checkAll) {
        this.isIndeterminate = false
        for (let i = 0; i < this.dialog.tagLists.length; i++) {
          if (this.orgin.dataList.indexOf(this.dialog.tagLists[i]) != -1) {
            this.isIndeterminate = true
            break
          }
        }
      }
    },
    // 判断当前是否可选（超过最大限制）
    judgeDisable (event, item) {
      // 最大选中数0 不限制
      if (this.orgin.limit == 0) {
        return false
      }
      let nowNum
      if (this.orgin.attrs.type == 'user') {
        // 已选中人数
        nowNum = this.dialog.userNum + 1
        // 当前选中人数
        const itemNum = typeof this.orgin.labelDataList[item].personCount === 'number' ? this.orgin.labelDataList[item].personCount : 1
        // 当前选中人数+当前选择框人数大于最大选择人数
        if (
          nowNum + itemNum > this.orgin.limit &&
          !this.dialog.tagLists.includes(item)
        ) {
          // 单选，清空之前选中
          if (itemNum <= this.orgin.limit && this.orgin.limit == 1) {
            this.dialog.tagLists = []
            return false
          }
          message.warning(`选择已超过最大限制${this.orgin.limit}人`)
          if (event && event.preventDefault) {
            event.preventDefault() // 非IE浏览器
          } else {
            window.event.returnValue = false
          } // IE浏览器
          return true
          // 单选清空之前选中
        } else {
          // 确保单选时，当前部门下0人，未重置之前选中的人
          if (this.orgin.limit == 1 && !this.dialog.tagLists.includes(item)) {
            this.dialog.tagLists.splice(0, 1)
          }
          return false
        }
      } else {
        nowNum = this.dialog.tagLists.length
        // 当前选中部门数
        const itemNum = 1
        // 当前选中部门数+1 大于最大选择部门数
        if (nowNum + itemNum > this.orgin.limit && !this.dialog.tagLists.includes(item)) {
          // 单选，清空之前选中
          if (itemNum <= this.orgin.limit && this.orgin.limit == 1) {
            this.dialog.tagLists = []
            return false
          }
          message.warning(`选择已超过最大限制${this.orgin.limit}人`)
          if (event && event.preventDefault) {
            event.preventDefault() // 非IE浏览器
          } else {
            window.event.returnValue = false
          } // IE浏览器
          return true
        } else {
          return false
        }
      }
    },
    // 判断当前是否可全选（超过最大限制）
    judgeAllDisable (event, item) {
      // 最大选中数0 不限制
      if (this.orgin.limit == 0) {
        return
      }
      if (!item) {
        // 取消选择不判断
        return
      }
      let nowNum
      if (this.orgin.attrs.type == 'user') {
        // 已选中人数
        nowNum = this.dialog.userNum
        // 当前全选新增人数
        let itemNum = 0
        this.orgin.dataList.forEach((data) => {
          // 当前项选中
          if (!this.dialog.tagLists.includes(data)) {
            itemNum += typeof this.orgin.labelDataList[data].personCount === 'number' ? this.orgin.labelDataList[data].personCount : 1
          }
        })
        // 当前选中人数+当前选择框人数大于最大选择人数
        if (nowNum + itemNum > this.orgin.limit) {
          message.warning(`选择已超过最大限制${this.orgin.limit}人`)
          if (event && event.preventDefault) {
            event.preventDefault() // 非IE浏览器
          } else {
            window.event.returnValue = false
          } // IE浏览器
          return true
        } else {
          return false
        }
      } else {
        nowNum = this.dialog.tagLists.length
        // 当前全选新增部门数
        let itemNum = 0
        this.orgin.dataList.forEach((data) => {
          // 当前项选中
          if (!this.dialog.tagLists.includes(data)) {
            itemNum += 1
          }
        })
        // 当前选中部门数+1 大于最大选择部门数
        if (nowNum + itemNum > this.orgin.limit) {
          message.warning(`选择已超过最大限制${this.orgin.limit}人`)
          if (event && event.preventDefault) {
            event.preventDefault() // 非IE浏览器
          } else {
            window.event.returnValue = false
          } // IE浏览器
          return true
        } else {
          return false
        }
      }
    }
  }
}
</script>

<style lang="less" scoped>
.disabled {
  color: rgb(190, 188, 188);
  cursor: not-allowed;
}
.check-lists {
  overflow-y: auto;
}
::v-deep .ant-checkbox-wrapper {
  display: flex;
  align-items: center;
  height: 40px;
  line-height: 40px;
  padding-left: 20px;
  margin: 0;
  &:hover {
    background-color: #f1f1f1;
    cursor: pointer;
    .link-bottom::before {
      border-left: 1px solid #e5e5e5;
    }
  }
  .icon-user {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    width: 230px;
  }
  .icon-user i {
    display: inline-block;
    margin-right: 5px;
  }
  .link-bottom {
    text-align: center;
    width: 60px;
    height: 40px;
    line-height: 40px;
    position: relative;
    color: #999;
    &::before {
      content: "";
      position: absolute;
      height: 20px;
      left: 0;
      top: 10px;
      border-left: 1px solid #f1f1f1;
    }
    &:hover {
      color: #409eff;
    }
  }
  &.ant-checkbox-wrapper-checked {
    .link-bottom {
      color: rgb(190, 188, 188);
      cursor: not-allowed;
    }
  }
}
</style>
